/*
 * SplashActivity.java
 *
 * Copyright(c) IronOne Technologies (Pvt) Ltd.  All Rights Reserved.
 * This software is the proprietary information of IronOne Technologies (Pvt) Ltd.
 *
 */
package com.ironone.streaming;

import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Session;
import com.facebook.SessionState;
import com.ironone.streaming.application.CusAlrtBtnTypes;
import com.ironone.streaming.application.CusAlrtIconTypes;
import com.ironone.streaming.application.CustomAlertDialog;
import com.ironone.streaming.application.FormObject;
import com.ironone.streaming.application.MainApplication;
import com.ironone.streaming.comm.HTTPManager;
import com.ironone.streaming.comm.NetworkCheck;
import com.ironone.streaming.exception.ExceptionHandler;
import com.ironone.streaming.model.ModelMapper;
import com.ironone.streaming.model.ResponseDataModel;

/**
 * { This class shows the splash screen for the user }
 *
 * @Created on May 22, 2014 : 11:50:00 AM
 * @author Suren Manawatta
 */
public class SplashActivity extends Activity {
	TextView errorTextView;
	ImageButton retryButton_flame;
	ImageButton retryButton_circle;

	ImageView boarding_drop_ImageView;
	ImageView matrix_drop_imageView1;
	ImageView matrix_drop_imageView11;
	ImageView matrix_drop_imageView2;
	ImageView matrix_drop_imageView22;
	ImageView matrix_drop_imageView3;
	ImageView matrix_drop_imageView33;
	ImageView matrix_drop_imageView4;
	ImageView matrix_drop_imageView44;
	ImageView matrix_line_imageView;

	Animation leftRight;
	Animation updown;
	Animation updownMartix1;
	Animation updownMartix11;
	Animation updownMartix2;
	Animation updownMartix22;
	Animation updownMartix3;
	Animation updownMartix33;
	Animation updownMartix4;
	Animation updownMartix44;

	private Handler handler;
	Runnable runnable;

	// xmlData used in RadioPlayer.java file
	// static String xmlData;
	private static boolean showWiFiInfoMessage = false;
	private static boolean isFacebookLoggedIn = false;
	private static int waitingTimeInMiliseconds = 3000;
	int upDownAnimeSpeed = 900;
	int randomNo = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));		

			handler = new Handler();
			Random r = new Random();
			randomNo = r.nextInt(2); // Generates one or zero
			//randomNo = 0;  // Testing
			if (randomNo == 1) {
				setContentView(R.layout.splash);
			}else{
				setContentView(R.layout.splash2);
			}

			/* Create Animation */
			updown = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updown.setRepeatCount(Animation.INFINITE);

			updownMartix1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix1.setRepeatCount(Animation.INFINITE);
			updownMartix1.setInterpolator(new LinearInterpolator());
			updownMartix11 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix11.setRepeatCount(Animation.INFINITE);
			updownMartix11.setInterpolator(new LinearInterpolator());
			updownMartix2 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix2.setRepeatCount(Animation.INFINITE);
			updownMartix2.setInterpolator(new LinearInterpolator());
			updownMartix22 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix22.setRepeatCount(Animation.INFINITE);
			updownMartix22.setInterpolator(new LinearInterpolator());
			updownMartix3 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix3.setRepeatCount(Animation.INFINITE);
			updownMartix3.setInterpolator(new LinearInterpolator());
			updownMartix33 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix33.setRepeatCount(Animation.INFINITE);
			updownMartix33.setInterpolator(new LinearInterpolator());
			updownMartix4 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix4.setRepeatCount(Animation.INFINITE);
			updownMartix4.setInterpolator(new LinearInterpolator());
			updownMartix44 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.drop_fall_updown);
			updownMartix44.setRepeatCount(Animation.INFINITE);
			updownMartix44.setInterpolator(new LinearInterpolator());

			if (randomNo == 1) {
				boarding_drop_ImageView = (ImageView)findViewById(R.id.boarding_drop_imageView);
				/* Start Animation */
				updown.setDuration(upDownAnimeSpeed);  // 900 is the default value set on drop_fall_updown XML file
				boarding_drop_ImageView.startAnimation(updown);
			}else {
				matrix_drop_imageView1 = (ImageView)findViewById(R.id.matrix_drop_imageView1);
				matrix_drop_imageView11 = (ImageView)findViewById(R.id.matrix_drop_imageView11);
				matrix_drop_imageView2 = (ImageView)findViewById(R.id.matrix_drop_imageView2);
				matrix_drop_imageView22 = (ImageView)findViewById(R.id.matrix_drop_imageView22);
				matrix_drop_imageView3 = (ImageView)findViewById(R.id.matrix_drop_imageView3);
				matrix_drop_imageView33 = (ImageView)findViewById(R.id.matrix_drop_imageView33);
				matrix_drop_imageView4 = (ImageView)findViewById(R.id.matrix_drop_imageView4);
				matrix_drop_imageView44 = (ImageView)findViewById(R.id.matrix_drop_imageView44);

				matrix_line_imageView = (ImageView)findViewById(R.id.matrix_line_imageView);

				matrix_drop_imageView1.setVisibility(View.INVISIBLE);
				matrix_drop_imageView2.setVisibility(View.INVISIBLE);
				matrix_drop_imageView3.setVisibility(View.INVISIBLE);
				matrix_drop_imageView4.setVisibility(View.INVISIBLE);

				matrix_drop_imageView11.setVisibility(View.INVISIBLE);
				matrix_drop_imageView22.setVisibility(View.INVISIBLE);
				matrix_drop_imageView33.setVisibility(View.INVISIBLE);
				matrix_drop_imageView44.setVisibility(View.INVISIBLE);

				handler.removeCallbacks(runnable);

				handler.postDelayed(runnable = new Runnable() {
					@Override
					public void run() {
						leftRight = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.left_to_right_slide);
						updown.setRepeatCount(0);
						matrix_line_imageView.startAnimation(leftRight);
					}
				}, 0);

				handler.postDelayed(runnable = new Runnable() {
					@Override
					public void run() {
						if (randomNo != 1)
							animeCommon();			
					}
				}, 800);
			}	

			errorTextView = (TextView)findViewById(R.id.errorTextView);
			errorTextView.setVisibility(View.INVISIBLE);

			retryButton_flame = (ImageButton)findViewById(R.id.retryButton_flame);
			retryButton_circle = (ImageButton)findViewById(R.id.retryButton_circle);

			retryButton_flame.setVisibility(View.INVISIBLE);
			retryButton_circle.setVisibility(View.INVISIBLE);

			retryButton_circle.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					handler.removeCallbacks(runnable);

					if (randomNo == 1)
						boarding_drop_ImageView.clearAnimation();
					else {
						matrix_drop_imageView1.clearAnimation();
						matrix_drop_imageView11.clearAnimation();
						matrix_drop_imageView11.setVisibility(View.INVISIBLE);
						matrix_drop_imageView2.clearAnimation();
						matrix_drop_imageView22.clearAnimation();
						matrix_drop_imageView22.setVisibility(View.INVISIBLE);
						matrix_drop_imageView3.clearAnimation();
						matrix_drop_imageView33.clearAnimation();
						matrix_drop_imageView33.setVisibility(View.INVISIBLE);
						matrix_drop_imageView4.clearAnimation();
						matrix_drop_imageView44.clearAnimation();
						matrix_drop_imageView44.setVisibility(View.INVISIBLE);
					}
					errorTextView.setVisibility(View.INVISIBLE);

					/* Create Animation */
					Animation rotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_button);
					rotation.setRepeatCount(Animation.INFINITE);
					/* Start Animation */
					retryButton_circle.startAnimation(rotation);
					retryButton_circle.setEnabled(false);
					
					if (randomNo == 1){
						updown.setDuration(upDownAnimeSpeed);
						boarding_drop_ImageView.startAnimation(updown);
					}else {
						animeCommon();
					}
					//new DisplyRetryProgressRingAsync().execute();
					new CommonAsync().execute(1);
				}
			});

			// These2 functions called only once. return values 
			// goes to FO and reused until app closed
			MainApplication.getScreenDimensions(this);
			MainApplication.getScreenTextSize(this);

			new CommonAsync().execute(3);

		} catch (Exception e) {
<<<<<<< .mine
			// TODO: handle exception
			Toast.makeText(SplashActivity.this, e.getMessage() , Toast.LENGTH_LONG).show();
=======
			CustomAlertDialog alertDialog = new CustomAlertDialog(this, CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
>>>>>>> .r59
		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		try {
			super.onWindowFocusChanged(hasFocus);

			if(!hasFocus) return;

			LinearLayout.LayoutParams params = (LayoutParams) retryButton_flame.getLayoutParams();
			params.width = (int) (FormObject.getInstance().getScreenWidth() / 10);
			params.height = params.width;
			retryButton_flame.setLayoutParams(params);
			retryButton_circle.setLayoutParams(params);
		} catch (Exception e) {
		}
	}

	int animeDuration1 = 1400;
	int animeDuration2 = 2400;
	int animeDuration3 = 2000;
	int animeDuration4 = 1000;	
	private void animeCommon() {
		try {
			updownMartix1.setDuration(animeDuration1);
			matrix_drop_imageView1.setVisibility(View.VISIBLE);
			matrix_drop_imageView1.startAnimation(updownMartix1);

			updownMartix2.setDuration(animeDuration2);
			matrix_drop_imageView2.setVisibility(View.VISIBLE);
			matrix_drop_imageView2.startAnimation(updownMartix2);

			updownMartix3.setDuration(animeDuration3);
			matrix_drop_imageView3.setVisibility(View.VISIBLE);
			matrix_drop_imageView3.startAnimation(updownMartix3);

			updownMartix4.setDuration(animeDuration4);
			matrix_drop_imageView4.setVisibility(View.VISIBLE);
			matrix_drop_imageView4.startAnimation(updownMartix4);

			handler.removeCallbacks(runnable);

			handler.postDelayed(runnable = new Runnable() {
				@Override
				public void run() {
					updownMartix11.setDuration(animeDuration1);
					matrix_drop_imageView11.setVisibility(View.VISIBLE);				
					matrix_drop_imageView11.startAnimation(updownMartix11);
				}
			}, (animeDuration1/2));

			handler.postDelayed(runnable = new Runnable() {
				@Override
				public void run() {
					updownMartix22.setDuration(animeDuration2);
					matrix_drop_imageView22.setVisibility(View.VISIBLE);				
					matrix_drop_imageView22.startAnimation(updownMartix22);
				}
			}, (animeDuration2/2));

			handler.postDelayed(runnable = new Runnable() {
				@Override
				public void run() {
					updownMartix33.setDuration(animeDuration3);
					matrix_drop_imageView33.setVisibility(View.VISIBLE);			
					matrix_drop_imageView33.startAnimation(updownMartix33);
				}
			}, (animeDuration3/2));

			handler.postDelayed(runnable = new Runnable() {
				@Override
				public void run() {
					updownMartix44.setDuration(animeDuration4);
					matrix_drop_imageView44.setVisibility(View.VISIBLE);				
					matrix_drop_imageView44.startAnimation(updownMartix44);
				}
			}, (animeDuration4/2));
		} catch (Exception e) {
<<<<<<< .mine
			// TODO Auto-generated catch block
			Toast.makeText(SplashActivity.this, e.getMessage() , Toast.LENGTH_LONG).show();
=======
			CustomAlertDialog alertDialog = new CustomAlertDialog(this, CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
>>>>>>> .r59
		}
	}

	public static boolean networkOk = false;
	public class CommonAsync extends AsyncTask<Integer, Void, Integer> {

		@Override
		protected Integer doInBackground(Integer... arg0) {
			try {
				int inc = 0;
				while (inc < arg0[0]) {
					inc++;
					if(NetworkCheck.isNetworkAvailable(getApplicationContext())) {
						networkOk = true;
						break;
					}else {
						try {
							Thread.sleep(waitingTimeInMiliseconds);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			} catch (Exception e) {
			}
			return arg0[0];
		}

		@Override
		protected void onPostExecute(Integer retryCount) {
			try {			
				if(networkOk){
					if(NetworkCheck.getNetworkType(SplashActivity.this) != 1){
						//errorTextView.setText(R.string._enable_wi_fi_info_message);
						//errorTextView.setVisibility(View.VISIBLE);
						//TODO: custom toast
						Toast.makeText(SplashActivity.this, R.string._enable_wi_fi_info_message, Toast.LENGTH_LONG).show();
						showWiFiInfoMessage = true;
					}

					// Start Facebook Login
					Session.openActiveSession(SplashActivity.this, false, new Session.StatusCallback() {
						// Callback when session changes state
						@Override
						public void call(Session session, SessionState state, Exception exception) {
							if (state.isOpened()){
								isFacebookLoggedIn = true;
								FormObject.getInstance().setFbLoginStatus(true);
							}
						}
					});

					//initDataManager = new InitDataManager(SplashActivity.this);
					
					//Toast.makeText(SplashActivity.this, FormObject.getInstance().getDataVersion()+" daver", Toast.LENGTH_LONG).show();
										
					new SplashAsync().execute();
				} else{
					if (randomNo == 1){
						boarding_drop_ImageView.setVisibility(View.INVISIBLE);
						boarding_drop_ImageView.clearAnimation();
						boarding_drop_ImageView.setVisibility(View.VISIBLE);
					}else {
						matrix_drop_imageView1.clearAnimation();
						matrix_drop_imageView11.clearAnimation();
						matrix_drop_imageView11.setVisibility(View.INVISIBLE);
						matrix_drop_imageView2.clearAnimation();
						matrix_drop_imageView22.clearAnimation();
						matrix_drop_imageView22.setVisibility(View.INVISIBLE);
						matrix_drop_imageView3.clearAnimation();
						matrix_drop_imageView33.clearAnimation();
						matrix_drop_imageView33.setVisibility(View.INVISIBLE);
						matrix_drop_imageView4.clearAnimation();
						matrix_drop_imageView44.clearAnimation();
						matrix_drop_imageView44.setVisibility(View.INVISIBLE);
					}

					retryButton_circle.setEnabled(true);
					retryButton_circle.setVisibility(View.VISIBLE);
					retryButton_circle.clearAnimation();
					errorTextView.setVisibility(View.VISIBLE);
					retryButton_flame.setVisibility(View.VISIBLE);
					showWiFiInfoMessage = false;

					handler.removeCallbacks(runnable);
				}
			} catch (Exception e) {
<<<<<<< .mine
				// TODO Auto-generated catch block
				Toast.makeText(SplashActivity.this, e.getMessage() , Toast.LENGTH_LONG).show();
=======
				CustomAlertDialog alertDialog = new CustomAlertDialog(SplashActivity.this, CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
				alertDialog.setTitleText(getString(R.string.what_the_duck_));
				alertDialog.setMessageText(getString(R.string.something_snapped));			
				alertDialog.show();
>>>>>>> .r59
			}
		}
	}

	public static boolean initSuccess = false;
	public class SplashAsync extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			try {
				//xmlData = initDataManager.getXML().trim();
				HTTPManager httpmanager = new HTTPManager(SplashActivity.this);
				ResponseDataModel responseModel = httpmanager.getInitServiceData();

				if(responseModel.isError && responseModel.responseData == null){
					return responseModel.errorMessage;
				}

				if(ModelMapper.getGeneralDataModel(responseModel) == null){
					return getString(R.string.error_jsonexception);
				}else{
					initSuccess = true;
					MainApplication.foSaveChanges(SplashActivity.this);
				}

				// ShowMessage : This will wait few seconds so user can read the Wi-Fi info message
				if(!responseModel.isError && showWiFiInfoMessage) {
					try {
						Thread.sleep(waitingTimeInMiliseconds);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			} catch (Exception e) {
				return getString(R.string.error_general);
			}
			return null;
		}

		@Override
		protected void onPostExecute(String data) {
			try {
				Intent i = null;

				if (initSuccess) {
					if (isFacebookLoggedIn) {
						i = new Intent(SplashActivity.this,	RadioPlayerActivity.class);
					} else {
						i = new Intent(SplashActivity.this, InitLoginActivity.class);
					}					
					startActivity(i);					
					finish();
				} else{
					retryButton_circle.setEnabled(true);
					retryButton_circle.setVisibility(View.VISIBLE);
					retryButton_circle.clearAnimation();
					errorTextView.setText(R.string.splash_retry);
					errorTextView.setVisibility(View.VISIBLE);
					retryButton_flame.setVisibility(View.VISIBLE);
					showWiFiInfoMessage = false;

					handler.removeCallbacks(runnable);
					
					if (randomNo == 1)
						boarding_drop_ImageView.clearAnimation();
					else {
						matrix_drop_imageView1.clearAnimation();
						matrix_drop_imageView11.clearAnimation();
						matrix_drop_imageView11.setVisibility(View.INVISIBLE);
						matrix_drop_imageView2.clearAnimation();
						matrix_drop_imageView22.clearAnimation();
						matrix_drop_imageView22.setVisibility(View.INVISIBLE);
						matrix_drop_imageView3.clearAnimation();
						matrix_drop_imageView33.clearAnimation();
						matrix_drop_imageView33.setVisibility(View.INVISIBLE);
						matrix_drop_imageView4.clearAnimation();
						matrix_drop_imageView44.clearAnimation();
						matrix_drop_imageView44.setVisibility(View.INVISIBLE);
					}				
					Thread.sleep(300);
					
					if(data == null || data.equals(""))
						data = getString(R.string.error_general);
					
					CustomAlertDialog alertDialog = new CustomAlertDialog(SplashActivity.this, CusAlrtBtnTypes.OK, CusAlrtIconTypes.WIZERD);
					alertDialog.setTitleText(getString(R.string.you_shall_not_pass));
					alertDialog.setMessageText(data);
					alertDialog.show();
				}
			} catch (Exception e) {
<<<<<<< .mine
				// TODO Auto-generated catch block
				Toast.makeText(SplashActivity.this, e.getMessage() , Toast.LENGTH_LONG).show();
=======
				CustomAlertDialog alertDialog = new CustomAlertDialog(SplashActivity.this, CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
				alertDialog.setTitleText(getString(R.string.what_the_duck_));
				alertDialog.setMessageText(getString(R.string.something_snapped));			
				alertDialog.show();
>>>>>>> .r59
			}
		}
	}
}